import json

from django.http import JsonResponse

from mech_manage.models import Person


def dispatcher(request):
    # 将请求同意放在request的params中
    print(request.body)
    if request.method == 'GET':
        request.params = request.GET
    elif request.method in ['POST', 'PUT', 'DELETE']:
        request.params = json.loads(request.body)

    # 根据不同的action分派给不同的函数进行处理
    action = request.params['action']
    if action == 'find_person':
        return find_person(request)
    elif action == 'list_person':
        return list_person(request)
    elif action == 'add_person':
        return add_person(request)
    elif action == 'modi_person':
        return modi_person(request)
    elif action == 'del_person':
        return del_person(request)

    else:
        return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'}, json_dumps_params={'ensure_ascii': False})


def find_person(request):
    # 读取传来的用户名密码

    try:
        uname = request.params['name']
        upassword = request.params['password']
        person = Person.objects.get(Pname=uname, Ppassword=upassword)
        return JsonResponse({
            'ret': 0
        }, json_dumps_params={'ensure_ascii': False})
    except Person.DoesNotExist:
        return JsonResponse({
            'ret': 1,
            'msg': f'用户名或密码错误，请重新输入'
        }, json_dumps_params={'ensure_ascii': False})


def list_person(request):
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    qs = Person.objects.values()
    # 将 QuerySet 对象 转化为 list 类型
    # 否则不能 被 转化为 JSON 字符串
    retlist = list(qs)
    return JsonResponse({'ret': 0, 'retlist': retlist}, json_dumps_params={'ensure_ascii': False})


def add_person(request):
    info = request.params['data']
    # 从请求消息中获取要添加的人员信息，并插入到数据库，返回值就是被插入的记录对象
    try:
        record = Person.objects.create(Plevel=info['level'],
                                       Pname=info['name'],
                                       Ppassword=info['password'],
                                       Pdepartment=info['department'],
                                       Psort=info['sort'],
                                       Pstate=info['state'],
                                       Pstarttime=info['starttime'],
                                       Pendtime=info['endtime'],
                                       )
        return JsonResponse({'ret': 0, 'id': record.id}, json_dumps_params={'ensure_ascii': False})
    except:
        return JsonResponse({'ret': 1, 'msg': "操作失败，信息不全"}, json_dumps_params={'ensure_ascii': False})


def modi_person(request):
    personid = request.params['id']

    newdata = request.params['newdata']

    try:
        person = Person.objects.get(id=personid)
    except Person.DoesNotExist:
        return JsonResponse({
            'ret': 1,
            'msg': f'id为‘{personid}’的部门不存在'
        }, json_dumps_params={'ensure_ascii': False})
    """
    原有写法
    """
    # if 'name' in newdata:
    #     person.Pname = newdata['name']
    # if 'level' in newdata:
    #     person.Plevel = newdata['level']
    # if 'password' in newdata:
    #     person.Ppassword = newdata['password']
    # if 'department' in newdata:
    #     person.Pdepartment = newdata['department']
    # if 'sort' in newdata:
    #     person.Psort = newdata['sort']
    # if 'state' in newdata:
    #     person.Pstate = newdata['state']
    # if 'starttime' in newdata:
    #     person.Pstarttime = newdata['starttime']
    # if 'endtime' in newdata:
    #     person.Pendtime = newdata['endtime']
    # """
    """
    效率写法
    """
    for keys in newdata.keys():
        # print(keys)
        # print("person.P"+keys+"=newdata['"+keys+"']")
        if len(keys) > 15:
            return JsonResponse({'ret': 1,
                                 'msg': f'侦测到潜在的入侵行为'
                                 }, json_dumps_params={'ensure_ascii': False})
        exec("person." + keys + "=newdata['" + keys + "']")
        exec("print(person." + keys + ")")
    # """
    person.save()

    return JsonResponse({'ret': 0}, json_dumps_params={'ensure_ascii': False})


def del_person(request):
    personid = request.params['id']

    try:
        person = Person.objects.get(id=personid)
    except Person.DoesNotExist:
        return JsonResponse({
            'ret': 1,
            'msg': f'要删除的人员不存在'
        }, json_dumps_params={'ensure_ascii': False})
    # delete 方法就将该记录从数据库中删除了
    person.delete()

    return JsonResponse({'ret': 0}, json_dumps_params={'ensure_ascii': False})
